import { defineStore } from 'pinia'
import { darkTheme, lightTheme } from 'naive-ui'
import dayjs from 'dayjs'
import type { BuiltInGlobalTheme } from 'naive-ui/es/themes/interface'
import type { RemindType, RecordCompletionType } from '@/api/interface'

export const useAppStore = defineStore('app', {
  state: () => ({
    theme: 'light',
    remind: [] as RemindType[],
    recordCompletion: [] as RecordCompletionType[]
  }),
  persist: [
    {
      pick: ['theme', 'remind', 'recordCompletion'],
      storage: localStorage
    }
  ],
  actions: {
    // 切换theme
    switchTheme(theme: 'light' | 'dark') {
      this.theme = theme
      window.ipcRenderer.send('set-theme', theme)
    },
    // 添加提醒
    addRemind(item: RemindType) {
      this.remind.push(item)
    },
    // 删除提醒
    deleteRemind(id: number) {
      this.remind = this.remind.filter((item) => item.id !== id)
    },
    addRecordCompletion(item: RecordCompletionType) {
      this.recordCompletion.push(item)
    },
    // 添加某一天的打卡日期
    addRecordCompletionDate(id: number) {
      const date = dayjs().format('YYYY-MM-DD')
      this.recordCompletion.forEach((item) => {
        if (item.id === id) {
          item.history.push({ id: Date.now(), date, data: [] })
          return
        }
      })
    },
    // 添加打卡记录
    addRecordCompletionItem(id: number, date_index: number) {
      const time = Date.now()
      this.recordCompletion.forEach((item) => {
        if (item.id === id) {
          item.history[date_index].data.push({
            id: time,
            time
          })
        }
      })
    },
    // 删除打卡记录
    deleteRecordCompletion(id: number) {
      this.recordCompletion = this.recordCompletion.filter(
        (item) => item.id !== id
      )
    },
    // 删除某次打卡记录
    deleteRecordCompletionItem(index: number, index2: number, index3: number) {
      this.recordCompletion[index].history[index2].data.splice(index3, 1)
      // 如果打卡记录为空，则删除整个打卡记录
      if (this.recordCompletion[index].history[index2].data.length === 0) {
        this.recordCompletion[index].history.splice(index2, 1)
      }
    }
  },
  getters: {
    currentTheme(): BuiltInGlobalTheme {
      return this.theme === 'light' ? lightTheme : darkTheme
    }
  }
})
